import { ref, reactive } from 'vue'
import type { Police } from '@/types/police'
import { WEBSOCKET_CONFIG } from '@/config/constants'

// 本地存储键名
const STORAGE_KEY = 'police_data_list'

// WebSocket连接状态
export const wsConnected = ref(false)
export const wsError = ref<string | null>(null)

// Police数据列表
export const policeList = ref<Police[]>([])

// 从localStorage加载数据
const loadPoliceData = (): Police[] => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      return JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载Police数据失败:', error)
  }
  return []
}

// 保存数据到localStorage
const savePoliceData = (data: Police[]) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch (error) {
    console.error('保存Police数据失败:', error)
  }
}

// 添加新的Police数据 - 直接按WebSocket接收频率更新
export const addPoliceData = (newData: Police) => {
  // 添加时间戳
  newData.timestamp = Date.now()

  // 数据范围检查，超出范围的数据设为null
  const dataRanges = {
    speed: { min: 0, max: 200 },
    kmv: { min: 0, max: 9999 },
    zig: { min: -600, max: 600 },
    hei: { min: 5000, max: 6600 },
    mohao: { min: 0, max: 20 },
    fVot: { min: 25, max: 30 },
    fPress: { min: 0, max: 300 },
    fVibration: { min: 0, max: 50 }
  }

  // 应用数据范围过滤，立即处理
  const processedData = { ...newData }

  if (typeof processedData.speed === 'number') {
    processedData.speed = (processedData.speed >= dataRanges.speed.min && processedData.speed <= dataRanges.speed.max)
      ? processedData.speed : null
  }

  if (typeof processedData.zig === 'number') {
    processedData.zig = (processedData.zig >= dataRanges.zig.min && processedData.zig <= dataRanges.zig.max)
      ? processedData.zig : null
  }

  if (typeof processedData.hei === 'number') {
    processedData.hei = (processedData.hei >= dataRanges.hei.min && processedData.hei <= dataRanges.hei.max)
      ? processedData.hei : null
  }

  if (typeof processedData.mohao === 'number') {
    processedData.mohao = (processedData.mohao >= dataRanges.mohao.min && processedData.mohao <= dataRanges.mohao.max)
      ? processedData.mohao : null
  }

  if (typeof processedData.fVot === 'number') {
    processedData.fVot = (processedData.fVot >= dataRanges.fVot.min && processedData.fVot <= dataRanges.fVot.max)
      ? processedData.fVot : null
  }

  if (typeof processedData.fPress === 'number') {
    processedData.fPress = (processedData.fPress >= dataRanges.fPress.min && processedData.fPress <= dataRanges.fPress.max)
      ? processedData.fPress : null
  }

  if (typeof processedData.fVibration === 'number') {
    processedData.fVibration = (processedData.fVibration >= dataRanges.fVibration.min && processedData.fVibration <= dataRanges.fVibration.max)
      ? processedData.fVibration : null
  }

  // 检查是否已存在相同ID的数据，如果存在则更新，否则添加
  const existingIndex = policeList.value.findIndex(item => item.id === processedData.id)

  if (existingIndex !== -1) {
    // 更新现有数据
    policeList.value[existingIndex] = { ...processedData }
  } else {
    // 添加新数据到列表开头
    policeList.value.unshift(processedData)
  }

  // 限制列表长度，避免数据过多
  if (policeList.value.length > 1000) {
    policeList.value = policeList.value.slice(0, 1000)
  }

  // 持久化存储
  savePoliceData(policeList.value)
}

// 清空Police数据
export const clearPoliceData = () => {
  policeList.value = []
  savePoliceData([])
}

// WebSocket实例
let websocket: WebSocket | null = null

// WebSocket连接配置
export const connectWebSocket = (url?: string) => {
  // 使用配置中的默认URL或传入的自定义URL
  const defaultUrl = `${WEBSOCKET_CONFIG.BASE_URL}${WEBSOCKET_CONFIG.ENDPOINTS.POLICE}`
  const wsUrl = url || defaultUrl
  // 如果已有连接，先关闭
  if (websocket) {
    websocket.close()
  }

  try {
    websocket = new WebSocket(wsUrl)

    websocket.onopen = () => {
      console.log('WebSocket连接已建立')
      wsConnected.value = true
      wsError.value = null
    }

    websocket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data) as Police
        console.log('收到Police数据:', data)
        addPoliceData(data)
      } catch (error) {
        console.error('解析WebSocket数据失败:', error)
        wsError.value = '数据解析错误'
      }
    }

    websocket.onerror = (error) => {
      console.error('WebSocket错误:', error)
      wsConnected.value = false
      wsError.value = 'WebSocket连接错误'
    }

    websocket.onclose = (event) => {
      console.log('WebSocket连接已关闭:', event.code, event.reason)
      wsConnected.value = false

      // 如果不是主动关闭，尝试重连
      if (event.code !== 1000) {
        wsError.value = 'WebSocket连接断开'
        setTimeout(() => {
          console.log('尝试重连WebSocket...')
          connectWebSocket(wsUrl)
        }, 5000) // 5秒后重连
      }
    }

  } catch (error) {
    console.error('创建WebSocket连接失败:', error)
    wsError.value = 'WebSocket创建失败'
  }
}

// 断开WebSocket连接
export const disconnectWebSocket = () => {
  if (websocket) {
    websocket.close(1000, '主动断开连接')
    websocket = null
  }
  wsConnected.value = false
  wsError.value = null
}

// 初始化数据
export const initPoliceService = () => {
  // 加载持久化数据
  policeList.value = loadPoliceData()
  console.log('已加载Police数据:', policeList.value.length, '条')
}

// 获取最新的Police数据
export const getLatestPoliceData = (): Police | null => {
  if (policeList.value.length === 0) return null
  return policeList.value[0]
}

// 根据ID获取Police数据
export const getPoliceById = (id: number): Police | null => {
  return policeList.value.find(item => item.id === id) || null
}